package com.system.log;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import javax.jws.WebParam;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.CodeSignature;

public class LogMethodExecutionHelper {
	public static String getArguments(ProceedingJoinPoint pjp) {
		Class targetClass = pjp.getTarget().getClass();
		Signature signature = pjp.getSignature();
		Object[] args = pjp.getArgs();
		String[] paramNames = new String[args.length];
		if (signature instanceof CodeSignature) {
			CodeSignature codeSignature = (CodeSignature) signature;
			Class[] parameterTypes = codeSignature.getParameterTypes();
			Class[] targetInterfaces = targetClass.getInterfaces();
			for (Class targetInterface : targetInterfaces) {
				try {
					Method method = targetInterface.getMethod(signature
							.getName(), parameterTypes);
					Annotation[][] paramAnnotationss = method
							.getParameterAnnotations();
					for (int i = 0; i < paramAnnotationss.length; i++) {
						Annotation[] paramAnnotations = paramAnnotationss[i];
						for (Annotation paramAnnotation : paramAnnotations) {
							if (paramAnnotation instanceof WebParam) {
								WebParam wp = (WebParam) paramAnnotation;
								paramNames[i] = wp.name();
								break;
							}
						}

					}
				} catch (SecurityException e) {
				} catch (NoSuchMethodException e) {
				}
			}
			for (int i = 0; i < paramNames.length; i++) {
				if (paramNames[i] == null) {
					paramNames[i] = parameterTypes[i].getSimpleName();
				}
			}
		}
		StringBuilder argumentsBuilder = new StringBuilder();
		for (int i = 0; i < args.length; i++) {
			if (paramNames[i] != null) {
				argumentsBuilder.append(paramNames[i]);
				argumentsBuilder.append(":");
			}
			argumentsBuilder.append(args[i]);
			argumentsBuilder.append(", ");
		}
		if (args.length > 0) {
			int bufferLength = argumentsBuilder.length();
			argumentsBuilder.delete(bufferLength - 2, bufferLength);
		}
		return argumentsBuilder.toString();
	}

	public static Long getResult(Object returnValue) {
		Long result = null;
		try {
			Method method = returnValue.getClass().getMethod("getResult");
			Object object = method.invoke(returnValue);
			if (object != null) {
				if (object instanceof Integer) {
					result = new Long(((Integer) object).intValue());
				} else if (object instanceof Long) {
					result = (Long) object;
				} else if (object instanceof String) {
					result = Long.valueOf((String) object);
				}
			}
		} catch (Exception e) {
		}
		return result;
	}
}
